from django.shortcuts import render, HttpResponse, redirect
from web.forms.account import LoginModelForm, SendSmsForm, LoginSMSForm, LoginForm
from django.http import JsonResponse
from utils.image_code import check_code
from io import BytesIO
from web import models
from django.db.models import Q
import uuid
import datetime


# 注册页面
def register(request):
    if request.method == "GET":
        form = LoginModelForm()

        return render(request, 'register.html', {'form': form})

    """基于form提交的输入"""
    # form = LoginModelForm(request.POST)
    #
    # if form.is_valid():
    #     user = form.save(commit=False)
    #     user.password = form.cleaned_data.get('password')
    #     user.save()
    #     return HttpResponse('ok')
    # else:
    #     print(form.errors)
    #     return render(request, 'layout/register.html', {'form': form})

    """基于ajax发送的数据"""
    form = LoginModelForm(data=request.POST)
    if form.is_valid():
        instance = form.save()
        # user = form.save(commit=False)
        # user.password = form.cleaned_data.get('password')
        # 获取用户信息对象
        # 价格策略的对象
        policy_object = models.PricePolicy.objects.filter(category=1, title="个人免费版").first()
        # 创建交易记录
        models.Transaction.objects.create(
            status=2,
            order=str(uuid.uuid4()),
            user=instance,
            price_policy=policy_object,
            count=0,
            price=0,
            start_datetime=datetime.datetime.now()
        )
        return JsonResponse({'status': True, 'data': '/login_sms/'})

    return JsonResponse({'status': False, 'error': form.errors})


# 验证码即手机校验
def send_sms(request):
    """发送短信"""
    print(request.GET)
    form = SendSmsForm(request, data=request.GET)
    # 校验手机号：不能为空,格式是否正确
    if form.is_valid():
        return JsonResponse({'status': True})
    return JsonResponse({'status': False, 'error': form.errors})


def login_sms(request):
    if request.method == "GET":
        form = LoginSMSForm()
        return render(request, 'login_sms.html', {'form': form})

    form = LoginSMSForm(request.POST)
    if form.is_valid():
        request.session['user_id'] = form.cleaned_data.get('mobile_phone').id
        request.session.set_expiry(60 * 60 * 24 * 14)
        return JsonResponse({'status': True, 'data': '/index/'})
    else:
        print(form.errors)
        return JsonResponse({'status': False, 'error': form.errors})


def login(request):
    if request.method == "GET":
        form = LoginForm(request)
        return render(request, 'login.html', {'form': form})
    form = LoginForm(request, data=request.POST)
    if form.is_valid():
        username = form.cleaned_data.get('username')
        password = form.cleaned_data.get('password')

        # 用户名或手机号登录，用到了Q函数(相当于|或)
        user_object = models.UserInfo.objects.filter(Q(email=username) | Q(mobile_phone=username)).filter(
            password=password).first()
        if user_object:
            request.session['user_id'] = user_object.id
            request.session.set_expiry(60 * 60 * 24 * 14)
            return redirect('index')
        # 用于添加错误信息
    print(form.errors)
    form.add_error('username', '用户名或密码错误')
    return render(request, 'login.html', {'form': form})


def image_code(request):
    image_object, code = check_code()
    # 通过session保存验证码进行验证
    request.session['image_code'] = code
    # 超时时间
    request.session.set_expiry(60)

    # 保存在内存中
    stream = BytesIO()
    image_object.save(stream, 'png')

    return HttpResponse(stream.getvalue())


def logout(request):
    request.session.flush()
    return redirect('index')
